import express from 'express';
import Ret, { RetCode } from '../../../bean/code/Ret';
const app = express();
import { urlEncode, excludeEmpty } from '../../../utils/index';
import { db, Sequelize } from '../../../dao/config/index';
import { converPage } from '../../../bean/page';
import { error } from '../../../utils/logger';
const User = require("../../../dao/models/f_user")(db, Sequelize);
const Product = require("../../../dao/models/f_product")(db, Sequelize);
const UserProductRelation = require("../../../dao/models/f_user_product_relation")(db, Sequelize);

UserProductRelation.belongsTo(Product, {
  forignKey: "product_id",
  as: "product"
})
/**
 * 根据获取指定商品 暂时只有一款
 */
app.get("/getSpecialProduct", async (req, res) => {
  const product = await Product.find({
    where: { type: 1 }
  });
  res.json(Ret(RetCode.SUCCESS).setData(product));
})
/**
 * 根据用户 查询出剩余可购买件数
 */
app.get("/getRemainingProductCounts", async (req, res) => {
  const { userId, productId } = req.query;
  try {
    const promiseRes = await Promise.all([
      UserProductRelation.findOrCreate({
        where: { userId, productId }, default: { userId, productId, count: 0 }
      }).spread(m => m),
      Product.findById(productId)]);
    const relationModel = promiseRes[0], productModel = promiseRes[1];
    const { count } = relationModel, { purchaseLimit = 0 } = productModel;
    const leftover = purchaseLimit - count;
    res.json(Ret(RetCode.SUCCESS).setData({ leftover }));
  } catch (e) {
    error(e);
  }

})

export default app;
